package club.jdiy.admin.controller;

import club.jdiy.admin.entity.Menu;
import club.jdiy.admin.interceptor.GuestDisabled;
import club.jdiy.core.base.domain.Ret;
import club.jdiy.admin.entity.Role;
import club.jdiy.admin.service.MenuService;
import club.jdiy.admin.service.RoleService;
import club.jdiy.dev.dao.JDiyUiDao;
import club.jdiy.utils.ArrayUtils;
import club.jdiy.utils.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Controller("ManageRoleCtrl")
@RequestMapping(value = "mgmt/role")
public class RoleCtrl extends JDiyAdminCtrl<Role, RoleService> {
    @Override
    @GuestDisabled
    public Ret<?> remove(String[] id, HttpServletRequest request) {
        if (id.length == 1) {
            if ("1".equals(id[0])) return Ret.fail("超级管理员角色不允许删除！");
        }
        return super.remove(id, request);
    }

    @Override
    public String in(String id, ModelMap map, HttpServletRequest request) throws Exception {
        List<Menu> menus = menuService.findRootList();
        map.put("menuList", menus);
        Map<String, Set<String>> realmsMap = new LinkedHashMap<>();
        _realms(menus, realmsMap);
        map.put("realmsMap", realmsMap);


        return super.in(id, map, request);
    }

    private void _realms(List<Menu> ls, Map<String, Set<String>> realmsMap) {
        if (ls == null) return;
        for (Menu mm : ls) {
            Set<String> userRealms = StringUtils.hasText(mm.getRealms())
                    ? Arrays.stream(mm.getRealms().replaceAll("\r", "").replaceAll("\\n+", "\n").split("\n")).collect(Collectors.toCollection(LinkedHashSet::new))
                    : new LinkedHashSet<>();
            if (!StringUtils.isEmpty(mm.getType()) && !"url".equals(mm.getType())) {
                List<String> sysRealms = uiDao.getRealms(mm.getUid());
                realmsMap.put(mm.getId(), ArrayUtils.merge(sysRealms, userRealms));
            } else {
                realmsMap.put(mm.getId(), userRealms);
            }
            _realms(mm.getChildren(), realmsMap);
        }
    }

    @Override
    @ResponseBody
    @GuestDisabled
    public Ret<?> save(Role vo, HttpServletRequest request) throws Exception {
        try {
            service.logicSave(vo);
            return Ret.success();
        } catch (Exception ex) {
            return Ret.error(ex);
        }
    }

    @RequestMapping("json_byDept_")
    @ResponseBody
    public List<String[]> jsonListEmpty() {
        List<String[]> ret = new ArrayList<>();
        ret.add(new String[]{"", "=选择角色="});
        return ret;
    }


    @Resource
    private MenuService menuService;
    @Resource
    private JDiyUiDao uiDao;
}
